import requests
import execjs
import datetime, time

cookies = {
    'routeId': '.uc2',
    'Hm_lvt_489bd07e99fbfc5f12cbb4145adb0a9b': '1719836601,1719970772',
    'MALLSSID': '5A6D33475950346A4256304B4651616675336C4A6372464A57334364345A5754797444654C2B35787234384B4E5572566162396951376B4436762B694B75584A',
    'Hm_lpvt_489bd07e99fbfc5f12cbb4145adb0a9b': '1719980472',
}

headers = {
    'Accept': '*/*',
    'Accept-EncKey': 'UsBr+hL2801k2J1QoUwYug==',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    # 'Cookie': 'routeId=.uc2; Hm_lvt_489bd07e99fbfc5f12cbb4145adb0a9b=1719836601,1719970772; MALLSSID=5A6D33475950346A4256304B4651616675336C4A6372464A57334364345A5754797444654C2B35787234384B4E5572566162396951376B4436762B694B75584A; Hm_lpvt_489bd07e99fbfc5f12cbb4145adb0a9b=1719980472',
    'Origin': 'https://webapi.cninfo.com.cn',
    'Referer': 'https://webapi.cninfo.com.cn/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}

data = {
    'tdate': '2024-06-28',
    'market': 'SZE',
}


def get_latest_month():
    date_list = []
    begin_date = (datetime.datetime.now() - datetime.timedelta(days = 30)).strftime("%Y-%m-%d")
    end_date = datetime.datetime.now().strftime("%Y-%m-%d")
    cur = begin_date
    while cur <= end_date:
        date_list.append(cur)
        cur_date = datetime.datetime.strptime(cur, "%Y-%m-%d")
        cur_date += datetime.timedelta(days = 1)
        cur = cur_date.strftime("%Y-%m-%d")

    return date_list


def get_latest_month_data():
    js_code = open('.\code.js', 'r', encoding='utf-8').read()
    ctx = execjs.compile(js_code)
    trade_data = []
    for date in get_latest_month():
        accept_key = ctx.call('getResCode')
        headers['Accept-EncKey'] = accept_key
        data['tdate'] = date
        response = requests.post('https://webapi.cninfo.com.cn/api/sysapi/p_sysapi1007', cookies=cookies, headers=headers, data=data, verify=False).json()
        if response['resultmsg'] != "success":
            print("request failed, date = ", date)
            pass

        records = response['records']
        for record in records:
            exchange = record['交易所']
            trade_date = record['交易日期']
            opening_price = record['开盘价']
            closing_price = record['收盘价']
            transactions = record['成交数量']
            min_price = record['最低价']
            max_price = record['最高价']
            diff = record['涨跌幅']
            stock_code = record['证券代码']
            stock_name = record['证券简称']

            trade_data.append((exchange, trade_date, opening_price, closing_price, transactions, min_price, max_price, diff, stock_code, stock_name))

    with open('transactions.txt','w', encoding = 'utf-8') as f:
        for record in trade_data:
            f.write(str(record))
            print(record)


get_latest_month_data()
